package com.gblfy.qywxin.controller;

import com.gblfy.qywxin.service.QywxInnerH5Service;
import com.gblfy.qywxin.utils.JWTUtils;
import com.gblfy.qywxin.vo.JsonData;
import com.gblfy.qywxin.vo.QywxInnerUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * H5统一管理入口
 *
 * @author gblfy
 * @date 2022-01-12
 */
@RestController
@RequestMapping("/h5")
public class H5Controller {
    private static final Logger logger = LoggerFactory.getLogger(H5Controller.class);

    @Autowired
    private QywxInnerH5Service qywxInnerH5Service;

    /**
     * 组装企微回调前端url
     *
     * @param corpId        企业ID
     * @param oauthCallback 回调url后缀
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping({"/oauthUrl"})
    JsonData oauthUrl(@RequestParam("corp_id") String corpId,
                      @RequestParam("oauth_callback") String oauthCallback) throws UnsupportedEncodingException {

        logger.info("accept corpId->{}", corpId);
        logger.info("accept oauthCallback->{}", oauthCallback);

        Map resData = new HashMap();

        //url编码处理
        String oauthRedirectUrl = URLEncoder.encode(oauthCallback, "utf-8");

        //组装回调url
        String oauthUrl = qywxInnerH5Service.getOauthUrl(corpId, oauthRedirectUrl);
        resData.put("oauth_url", oauthUrl);
        return JsonData.buildSuccess(resData);
    }

    /**
     * 通过corpId（企业ID）、企微回传code获取用户详情信息
     *
     * @param corpId 企业ID
     * @param code   企微回传code
     * @return
     */
    @RequestMapping("/oauthUser")
    JsonData oauthCallback(@RequestParam("corp_id") String corpId,
                           @RequestParam("code") String code) {

        logger.info("accept corpId->{}", corpId);
        logger.info("accept code->{}", code);

        //通过corpId（企业ID）、企微回传code获取用户详情信息
        Map result = qywxInnerH5Service.getOauthUser(corpId, code);

        //本案例仅从企业微信接口获取未从数据表中获取
        QywxInnerUser user = new QywxInnerUser();
        user.setCorpId(corpId);
        user.setUserId((String) result.get("userId"));
        String token = JWTUtils.geneJsonWebToken(user);

        result.put("token", token);
        return JsonData.buildSuccess(result);
    }
}
